package com.acme.bankapp.service.bank.listener.email;

/**
 * @author Alexander Kotov (kotov.alex.22@gmail.com)
 */
public class EmailWorker implements Runnable {
    private static final int BUSY_TIME = 1000;
    private final BankBlockingQueue<Email> blockingQueue;

    private void sendNotificationEmail(final Email email) {
        System.out.println("Notification has been send to " + email.toString());
    }

    public EmailWorker(final BankBlockingQueue<Email> blQueue) {
        this.blockingQueue = blQueue;
    }

    @Override
    public void run() {
        while (!Thread.currentThread().isInterrupted()) {
            try {
                Email email = blockingQueue.get();
                sendNotificationEmail(email);
                Thread.sleep(BUSY_TIME);
            } catch (InterruptedException e) {
                System.out.format("Worker %s has been interrupted%n", Thread.currentThread().getName());
                Email email = null;
                while ((email = blockingQueue.compareAndGet()) != null) {
                    sendNotificationEmail(email);
                }
                Thread.currentThread().interrupt();
            }
        }
    }
}
